package com.torres.system.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.torres.system.entity.VersionEntity;
import com.torres.system.service.ISystemService;
import com.torres.system.util.DateUtils;
import com.torres.system.util.FileUtils;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("/")
public class SystemController {
	
	@Value("${logging.path}")
	private String logPath;
	
	@Value("${server.servlet.context-path}")
	private String logFileName;

	@Autowired
	private ISystemService systemService;
	
	@GetMapping("/")
    @ApiOperation(value = "hello")
    public ResponseEntity<String> hello() {
        return new ResponseEntity<>("hello, world!", HttpStatus.OK);
    }
	
	@GetMapping("/version")
    @ApiOperation(value = "版本信息")
    public ResponseEntity<String> getVersion() {
		VersionEntity entity = systemService.getLastVersion();
        return new ResponseEntity<>(entity.getVersion(), HttpStatus.OK);
    }
	
	@GetMapping("/log/{level}/{strDate}")
    @ApiOperation(value = "日志信息")
    public ResponseEntity<String> getLogger(HttpServletResponse response, @PathVariable String level, @PathVariable String strDate, 
    		@RequestParam(defaultValue = "false") Boolean download, @RequestParam(defaultValue = "GB2312") String charset) {
		log.info("入参：[level={}, strDate={}, download={}, charset={}]", level, strDate, download, charset);
		String logFile = logPath + level;
		if (!FileUtils.fileEncodeUtf8.equals(charset.toUpperCase())) {
			charset = FileUtils.fileEncodeGbk;
		}
		if("1".equals(strDate)) {
			Date currentTime = new Date();
            String today =  DateUtils.date_sdf.get().format(currentTime);
			strDate = today + "-0";
		}
		switch (level) {
		case "all":
			logFile += logFileName + "." + strDate + ".log";
			break;
		case "error":
		case "info":
		case "warn":
		default:
			logFile += logFileName + "_" + level + "." + strDate + ".log";
			break;
		}
		File file = new File(logFile);
		if (file.exists()) {
			response.setHeader("content-type", "text/html;charset=" + charset);
			OutputStream os = null;
			BufferedReader br = null;
			byte[]  linefeed = "<br>".getBytes();
			try {
				br = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
				os = response.getOutputStream();
	            String line;
	            while ((line = br.readLine()) != null) {
	            	os.write(line.getBytes());
	            	os.write(linefeed);
	            }  
			} catch (IOException e) {
				log.error("读取日志文件错误", e);
			} finally {
				IOUtils.closeQuietly(br);
				IOUtils.closeQuietly(os);
			}
		}
		return new ResponseEntity<>("无数据" + logFile, HttpStatus.OK);
    }
}
